package com.doubleview;

import java.util.ArrayList;
import java.util.List;

/**
 * 数字字符串转为ip地址
 */
public class Solution_20 {

    /**
     * @param s string字符串
     * @return string字符串ArrayList
     */
    public ArrayList<String> restoreIpAddresses(String s) {
        // write code here
        // write code here
        if (s == null || s.length() < 3 || s.length() > 12) {
            return new ArrayList<>();
        }
        ArrayList<String> list = new ArrayList<>();
        backTrace(0, s, list, new StringBuilder());

        return list;
    }

    private void backTrace(int partNum, String s, List<String> list, StringBuilder midIp) {
        if (partNum == 4 || s.length() == 0) {
            if (partNum == 4 && s.length() == 0) {
                list.add(midIp.toString());
            }
            return;
        }
        for (int i = 0; i <= 2 && i < s.length(); i++) {
            if (i != 0 && s.charAt(0) == '0') {
                break;
            }
            String substring = s.substring(0, i + 1);
            if (Integer.valueOf(substring) <= 255) {
                if (midIp.length() != 0) {
                    substring = "." + substring;
                }
                midIp.append(substring);
                backTrace(partNum + 1, s.substring(i + 1), list, midIp);
                midIp.delete(midIp.length() - substring.length(), midIp.length());
            }
        }
    }
}